package com.example.demo2.controller;

import com.example.demo2.pojo.data.AdminDO;
import com.example.demo2.utils.MD5Utils;
import com.example.demo2.utils.Result;
import com.example.demo2.pojo.vo.AdminVO;
import com.example.demo2.service.AdminService;
import com.google.code.kaptcha.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;


import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/** 
 * <br/>
 * Created by weidong on 2020/02/02
 */
@Controller
public class LoginController {

	@Resource
	private AdminService adminService;

	@RequestMapping("/loginIn")
	public String LoginDO(String username, String password, String verify,
						  @SessionAttribute(Constants.KAPTCHA_SESSION_KEY) String rand, HttpSession session, Model model) {

		//引入MD5Utils使用md5加密

		if(verify != null && verify.toUpperCase().equals(rand.toUpperCase())){
			//获取当前的用户
			Subject subject = SecurityUtils.getSubject();
			//封装用户的登陆数据
			UsernamePasswordToken token = new UsernamePasswordToken(username,MD5Utils.md5(password));
			try {
				subject.login(token);//执行登录方法，如果没有异常说明OK
				return "home";
			} catch (UnknownAccountException e) {//用户名不存在
				model.addAttribute("msg","用户名错误");
				return "login";
			}catch (IncorrectCredentialsException e) {//密码不存在
				model.addAttribute("msg","密码错误");
				return "login";
			}
		}
		else{
			model.addAttribute("msg","验证码错误");
			return "login";
		}
	}
	@RequestMapping("/adminAdd")
	public String add(String username,String password) throws Exception {
		AdminVO adminVO=new AdminVO();
		adminVO.setUsername(username);
		adminVO.setPassword(MD5Utils.md5(password));
		adminVO.setIdentity("0");
		adminService.add(adminVO);
		return "login";
	}
	@RequestMapping("/400")
	public String LoginS(){
		return "400";
	}

	@RequestMapping("/register")
	public String Register(){
		return "register";
	}
	@RequestMapping("/user/logout")
	public  String Logout(){
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "redirect:/login";
	}
	@RequestMapping({"/","/login"})
	public String toLogin(){
		return "login";
	}
	@RequestMapping("/noauth")
	@ResponseBody
	public String unauthorized(){
		return "未经授权无法访问";
	}


}